<template>
    <el-dialog title="选择工程名称" :visible.sync="visible" fullscreen width="1020px" :close-on-click-modal="false">
        <div class="project-container">
            <div class="left">
                <el-tabs v-model="activeChapterType" @tab-click="handleClick">
                    <el-tab-pane label="章次" name="1"></el-tab-pane>
                    <el-tab-pane label="计日工" name="2"></el-tab-pane>
                </el-tabs>
                <div v-if="chapterList.length > 0" v-loading="chapterLoading" class="list">
                    <div
                        v-for="item in chapterList"
                        :key="item.code"
                        class="chapter-item"
                        :class="{ active: chapterCode === item.code}"
                        @click="handleChangeChapter(item)"
                    >
                        <span class="name g-line-1">{{ item.name }}</span>
                    </div>
                </div>
                <div v-else class="no-data">
                    <IconSvg icon-class="no-data2" class="icon"></IconSvg>
                    <span>暂无数据</span>
                </div>
            </div>
            <BasePage style="flex: 1;">
                <el-form slot="form" :inline="true" size="medium" label-width="104px" @submit.native.prevent>
                    <el-form-item label="清单子目编码">
                        <el-input v-model="form.listSubitemCode" placeholder="请输入" clearble></el-input>
                    </el-form-item>
                    <el-form-item label="清单子目名称">
                        <el-input v-model="form.listSubitemName" placeholder="请输入" clearble></el-input>
                    </el-form-item>
                    <el-form-item>
                        <BaseButton @click="handleFilter">查询</BaseButton>
                        <BaseButton type="second" @click="handleReset">重置</BaseButton>
                    </el-form-item>
                </el-form>

                <!--数据列表区-->
                <BaseTable
                    slot="table"
                    ref="table"
                    v-loading="listLoading"
                    :columns="columns"
                    :data="list"
                    row-key="id"
                    height="calc(100% - 30px)"
                    highlight-current-row
                    default-expand-all
                    :tree-props="{ children: 'childrenList', hasChildren: ''}"
                    @selection-change="handleSelectionChange"
                    @select="handleSelect"
                    @expand-change="handleExpandChange"
                >
                    <template #code="{ scope: { row } }">
                        <div class="icon-flex">
                            <IconSvg v-if="!row.expanded && row.expanded !== undefined && row.hasChildren === 1" icon-class="file" class="file-icon"></IconSvg>
                            <IconSvg v-if="(row.expanded || row.expanded === undefined) && row.hasChildren === 1" icon-class="file-open" class="file-icon"></IconSvg>
                            <IconSvg v-if="row.hasChildren === 2" icon-class="catalogue" class="catalogue-icon"></IconSvg>
                            {{ row.listSubitemCode }}
                        </div>
                    </template>
                </BaseTable>
                <!--分页组件-->
                <Pagination
                    slot="pagination"
                    :current-page.sync="page.pageNo"
                    :page-size.sync="page.pageSize"
                    :total="page.total"
                    @current-change="handleJumpPage"
                    @size-change="handleJumpPage"
                />
            </BasePage>
            <div class="right">
                <div>已选择 <span class="color-blue">{{ multipleSelection.length }}</span> 条清单子目</div>
                <ul class="selected-list-box">
                    <li v-for="item in multipleSelection" :key="item.id" class="selected-list">
                        <span>{{ item.listSubitemCode }} {{ item.listSubitemName }}</span>
                        <i class="el-icon-close delete-icon" @click="handleDelete(item.id)"></i>
                    </li>
                </ul>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <BaseButton type="second" @click="cancel">取消</BaseButton>
            <BaseButton @click="handleSubmit">确认</BaseButton>
        </div>
        
    </el-dialog>
</template>

<script>
import BasePage from '@/layouts/BasePage'
import { ContractModel } from '@/models'

export default {
    name: 'ProjectListDialog',
    components: {
        BasePage,
    },
    props: {
        id: {
            type: [String, Number],
            default: ''
        },
    },
    data() {
        return {
            model: new ContractModel(),
            visible: false,
            submitLoading: false,
            chapterLoading: false,
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            form: {
                listSubitemCode: '',
                listSubitemName: ''
            },
            chapterList: [],
            listLoading: false,
            columns: Object.freeze([
                {
                    attrs: {
                        type: 'selection',
                        width: '80',
                        selectable: (row) => {
                            // 只有不存在子项 且 单位不是总额的才能选择
                            return row.hasChildren === 2 && row.unitCode !== 'zonge'
                        },
                        'reserve-selection': true
                    }
                },
                {
                    slot: 'code',
                    attrs: {
                        prop: 'listSubitemCode',
                        label: '清单子目编码',
                        'min-width': '190',
                        'class-name': 'custom-td'
                    }
                },
                {
                    attrs: {
                        prop: 'listSubitemName',
                        label: '清单子目名称',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'unitSymbol',
                        label: '单位',
                        width: '90',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'quantity',
                        label: '数量',
                        width: '120',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'price',
                        label: '单价（元）',
                        width: '140',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'amount',
                        label: '合价（元）',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'remark',
                        label: '备注',
                        width: '140',
                        'show-overflow-tooltip': true
                    }
                }
            ]),
            list: [],
            multipleSelection: [],
            isHandlingSelection: false,
            activeChapterType: '1', // 要和合同那边的type1和2对应，这里因为组件要求必须是字符串，不影响查询
            chapterCode: '',
            filterIds: [] // 需要过滤掉的id
        }
    },
    methods: {
        findNodeById(treeData, id) {
            for (let i = 0; i < treeData.length; i++) {
                const node = treeData[i]
                if (node.id === id) {
                    return node
                }
                if (node.childrenList) {
                    const foundNode = this.findNodeById(node.childrenList, id)
                    if (foundNode) {
                        return foundNode
                    }
                }
            }
            return null
        },
        handleExpandChange(row, expanded) {
            row.expanded = expanded
        },
        async handleChangeChapter(item) {
            this.chapterCode = item.code
            this.activeTitleName = item.name

            this.page.pageNo = 1
            await this.getList()
            this.backfillTableSelected()
        },
        // 回显表格的选中状态数据
        backfillTableSelected() {
            const table = this.$refs.table.$refs.table
            if (this.multipleSelection.length > 0) {
                // 1、一定要先清除选中，否则切换表格时获取到的选中数据会出现混乱
                table.clearSelection()
                // 2、找到已经选中的数据，手动让当前行选中
                this.multipleSelection.forEach(item => {
                    const targetNode = this.findNodeById(this.list, item.id) // 根据id查找对应行数据
                    console.log(targetNode)
                    if (targetNode) {
                        // 使用$set确保Vue能追踪到这一变化
                        this.$nextTick(() => {
                            table.toggleRowSelection(targetNode, true) // 设置该行选中
                        })
                    }
                })
            }
        },
        async handleClick() {
            await this.getChapterList()
            if (this.chapterList.length === 0) { return }
            const active = this.chapterList[0] || {}

            this.handleChangeChapter(active)
        },
        // 章次列表
        getChapterList() {
            this.chapterLoading = true
            const data = {
                contractId: this.id,
                type: this.activeChapterType
            }
            return this.model
                .chapterListById(data)
                .then(res => {
                    this.chapterList = (res || []).map(item => {
                        let name = ''
                        if (this.activeChapterType === '1') {
                            name = item.listSubitemCode + '章 ' + item.listSubitemName
                        }
                        if (this.activeChapterType === '2') {
                            name = item.listSubitemName
                        }
                        return {
                            name,
                            code: item.listSubitemCode,
                            id: item.id
                        }
                    })
                })
                .finally(() => {
                    this.chapterLoading = false
                })
        },
        handleSelectionChange(val) {
            // 3、当选中数据发生变换时，检查是否有新增的选中数据，有则添加到multipleSelection中
            val.forEach(item => {
                if (!this.multipleSelection.some(m => m.id === item.id)) {
                    this.multipleSelection.push(item)
                }
            })
        },
        handleSelect(selection, row) {
            // 4、手动选择时，检查当前点击的数据是否在选中数据中，如果没有就是取消操作，从multipleSelection中删除
            if (!selection.some(m => m.id === row.id)) {
                const index = this.multipleSelection.findIndex(item => item.id === row.id)
                if (index !== -1) {
                    this.multipleSelection.splice(index, 1)
                }
            }
        },
        handleDelete(id) {
            // 5.1 删除右边选中数据
            const index = this.multipleSelection.findIndex(item => item.id === id)
            if (index !== -1) {
                this.multipleSelection.splice(index, 1)
            }
            // 5.2 取消表格选中数据
            const targetNode = this.findNodeById(this.list, id) // 根据id查找对应行数据
            if (targetNode) {
                this.$nextTick(() => {
                    this.$refs.table.$refs.table.toggleRowSelection(targetNode, false) // 取消选中行
                })
            }
        },
        handleDetail(row) {
            // 使用$router的resolve方法来构造目标路由的完整URL
            const targetUrl = this.$router.resolve({
                name: 'DailyMaintenanceTaskDetail',
                query: {
                    id: row.id,
                    code: row.code
                }
            }).href

            // 使用window.open在新标签页中打开该URL
            window.open(targetUrl, '_blank')
        },
        // 取消按钮
        cancel() {
            this.visible = false
        },
        async open(ids) {
            this.filterIds = ids
            this.visible = true
            // 默认显示工程量清单
            this.activeChapterType = '1'

            // 清楚列表数据和选中数据
            this.list = []
            this.multipleSelection = []

            // 获取左边的章次列表
            await this.getChapterList()
            if (this.chapterList.length === 0) { return }

            // 默认选中第一个章次
            const active = this.chapterList[0] || {}
            this.chapterCode = active.code

            // 清空表单
            this.reset()
            // 重新获取列表，并清空表格选项
            await this.getList()
            this.$nextTick(() => {
                this.$refs.table.$refs.table.clearSelection()
            })
        },
        reset() {
            this.form = {
                listSubitemCode: '',
                listSubitemName: ''
            }
            this.page.pageNo = 1
        },
        async handleReset() {
            this.reset()
            await this.getList()
            this.backfillTableSelected()
        },
        async handleFilter() {
            this.page.pageNo = 1
            await this.getList()
            this.backfillTableSelected()
        },
        async handleJumpPage() {
            await this.getList()
            this.backfillTableSelected()
        },
        // 子目次列表
        getList() {
            this.listLoading = true
            return this.model
                .quantitiesList({
                    contractId: this.id,
                    type: this.activeChapterType,
                    chapterSequenceCode: this.chapterCode,
                    nonIds: this.filterIds,
                    ...this.page,
                    ...this.form,
                })
                .then(res => {
                    this.list = res.list || []
                    this.page.total = res.totalCount
                    this.totalAmount = res.totalAmount
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        handleSubmit() {
            console.log(this.multipleSelection)
            const data = this.multipleSelection.map(item => {
                return {
                    ...item,
                    billQuantitiesType: item.type,
                    remark: '',
                    quantity: '' // 把数量清空，回填那里字段重复
                }
            })
            this.$emit('success', data)
            this.visible = false
        }
    }
}
</script>

<style lang="scss" scoped>

.project-container {
    margin-top: 16px;
    width: 100%;
    height: calc(100vh - 210px);
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;

    /* 替换默认展开收起图片 */
    ::v-deep {
        .el-table__expand-icon {
            width: 16px;
            height: 16px;
            background: url("~@/assets/images/zhankai.png") no-repeat;
            background-size: 100% 100%;
            margin-left: -20px;
            flex-shrink: 0;
            .el-icon-arrow-right {
                display: none;
            }
        }
        .el-table__expand-icon--expanded {
            transform: none;
            background: url("~@/assets/images/shouqi.png") no-repeat;
            background-size: 100% 100%;
            flex-shrink: 0;
        }
        .custom-td .cell {
            display: flex;
            align-items: center;
        }

        // 把多选功能隐藏，不然在多选和取消时，又会导致数据联动存在问题
        .el-table__header-wrapper .el-checkbox:before {
            content: '选择';
            display: block;
            cursor: default;
            font-weight: bold;
        }
        .el-table__header-wrapper .el-checkbox .el-checkbox__input {
            // visibility: hidden;
            display: none;
        }
    }
    .icon-flex {
        display: flex;
        align-items: center;
        line-height: 1.5;

        .file-icon {
            width: 22px;
            font-size: 22px;
            margin-right: 4px;
            flex-shrink: 0;
        }
        .catalogue-icon {
            width: 20px;
            font-size: 18px;
            margin-right: 4px;
            flex-shrink: 0;
        }
    }
}
.left {
    width: 280px;
    height: 100%;
    margin-right: 16px;
    flex-shrink: 0;
    border: 1px solid #f0f4f7;
    box-shadow: 0px 0px 4px 0px rgba(131, 145, 178, 0.14);
    padding: 24px 16px;
    .list {
        overflow-y: auto;
        max-height: 100%;
        margin-bottom: 16px;
        .chapter-item {
            padding: 0 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            line-height: 42px;
            cursor: pointer;
            &:hover,
            &.active {
                background-color: rgba(0, 98, 255, 0.06);
                color: #0162FF;
            }
            .btn {
                display: none;
                flex-shrink: 0;
            }
            &:hover .btn {
                display: block;
            }
        }
    }
}
.title-item {
    margin-left: 32px;
}

.right {
    width: 280px;
    height: 100%;
    margin-left: 16px;
    flex-shrink: 0;
    border: 1px solid #f0f4f7;
    box-shadow: 0px 0px 4px 0px rgba(131, 145, 178, 0.14);
    padding: 24px 16px;

    .selected-list-box {
        margin-top: 8px;
        overflow-y: auto;
        max-height: calc(100% - 30px);
    }
    .selected-list {
        display: flex;
        align-items: center;
        justify-content: space-between;
        line-height: 1.4;
        padding: 4px 0;
    }
    .delete-icon {
        padding: 8px;
        flex-shrink: 0;
        cursor: pointer;
        &:hover {
            font-weight: bold;
        }
    }
}

.no-data {
    color: #9090A0;
    font-size: 14px;
    text-align: center;
    padding: 100px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    .icon {
        font-size: 66px;
        padding-bottom: 12px;
        color: #c2c2c2;
    }
    .button {
        color: #0162FF;
        font-style: normal;
        cursor: pointer;
    }
}
</style>
